package org.easley.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.easley.pay.common.ApiResult;
import org.easley.pay.common.UserDto;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public final class WeiboPayViewUtil {
    public static final Map<String, UserDto> USER_MAP = new HashMap<>();
    private static final String file_path = "/data/data/user.json";

    private static ExecutorService executorService = Executors.newFixedThreadPool(10);

    static {
        try {
            String express = FileUtils.readFileToString(new File(file_path),"utf-8");
            if(StringUtils.isNotBlank(express)){
               List<UserDto> list = JSON.parseArray(express, UserDto.class);
               if(list!=null){
                   list.forEach(p->{
                       USER_MAP.put(p.getUser(),p);
                   });
               }
            }
        }catch (Exception e){
        }
    }



    public static ApiResult<String> addUser(String username, String password) {
        ApiResult<String> apiResult = ApiResult.build();
        try {
            WeiboPayLogin weiboPayLogin = getWeiboPayLogin(username, password);
            if(weiboPayLogin.getCookieSinaPassport()!=null && StringUtils.isNotBlank(weiboPayLogin.getCookieSinaPassport().toString())){
                UserDto userDto = new UserDto();
                userDto.setUser(username);
                userDto.setPassword(password);
                userDto.setCookie(weiboPayLogin.getCookieSinaPassport().toString());
                addMap(userDto);
            }else{
                System.out.println(String.format("用户：{} 登录失败", username));
                apiResult.error("登录失败");
            }
        } catch (Exception e) {
            apiResult.error(e.getMessage());
        }
        return apiResult;
    }

    public static void addMap(UserDto userDto){
        USER_MAP.put(userDto.getUser(), userDto);
        writeStringToFile();
    }

    public static void writeStringToFile(){
        try {
            FileUtils.writeStringToFile(new File(file_path), JSON.toJSONString(new ArrayList<UserDto>(USER_MAP.values())), "utf-8");
        }catch (Exception e){
        }
    }


    public static WeiboPayLogin getWeiboPayLogin(String username, String password){
        try{
            WeiboPayLogin weiboPayLogin = new WeiboPayLogin(username, password);
            weiboPayLogin.preLogin();
            // 登录新浪通行证抓包时获取的请求地址
            weiboPayLogin.login("https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)&_=" + System.currentTimeMillis());
            StringBuffer sb =new StringBuffer();
            sb.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                            .append("用户：")
                            .append(username)
                            .append("登录Cookie:")
                            .append(weiboPayLogin.getCookieSinaPassport().toString());
            System.out.println(sb.toString());

            return  weiboPayLogin;
        }catch (Exception e){
            System.out.println("登录微博失败："+ e);
        }
       return  null;
   }

    public static void delUser(String username) {
        USER_MAP.remove(username);
        writeStringToFile();
    }

    public static List<WeiboPayResult> queryAll(String startTime, String endTime) {
        Set<String> entrySet = USER_MAP.keySet();
        if (entrySet.isEmpty()) {
            System.out.println("USER_MAP 为空");
            return new ArrayList<>(2);
        }
        if(StringUtils.isBlank(startTime)){
            startTime = LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        List<Future<WeiboPayResult>> futures = new ArrayList<Future<WeiboPayResult>>();
        for (String username : entrySet) {
            if(StringUtils.isNotBlank(username)){
                WeiboPayResultTask task = new WeiboPayResultTask(username, startTime, endTime);
                futures.add(executorService.submit(task));
            }else{
                delUser(username);
            }
        }
        List<WeiboPayResult> results = new ArrayList<>();
        for (Future<WeiboPayResult> f : futures) {
            try {
                WeiboPayResult result =f.get();
               if(result!=null){
                   results.add(result);
               }
            } catch (Exception e) {
                System.out.println("查询微博失败："+ e);
            }
        }
        return results;
    }


    public static void main(String[] args) {
        String username ="=2019-12-05 21:07:17=2019-12-05 21:07:17";
        System.out.println(username.replaceAll(" ", "%20"));
    }
}
